package com.young.dynamicexcel.controller;

import com.young.dynamicexcel.common.dto.BaseResult;
import com.young.dynamicexcel.common.dto.DynamicExcelParam;
import com.young.dynamicexcel.service.DynamicExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @DESCRIPTION: excel动态导入导出Controller
 * @USER: Young
 */
@CrossOrigin
@RequestMapping("/dynamicExcel")
@RestController
public class DynamicExcelController {

    @Autowired
    private DynamicExcelService dynamicExcelService;

    /**
     * 通过数据库字段导出
     * @param tableName
     * @param fileName
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void exportExcel(String tableName, String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        dynamicExcelService.exportExcelByDatabase(tableName, fileName, false, request, response);
//        return BaseResult.success("导出成功");
    }

    /**
     * 通过数据库字段导入
     * @param tableName
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/import")
    public BaseResult importExcel(String tableName, MultipartFile file) throws Exception {

        dynamicExcelService.importExcelByDatabase(tableName,file.getInputStream());
        return BaseResult.success("导入成功");
    }

    /**
     * 通过model选择字段导出
     * @param dynamicExcelParam
     * @param request
     * @param response
     * @throws Exception
     */
    //http://localhost:8080/dynamicExcel/export2?entityName=apprExcelDemo&fileName=apprExcelDemo&headMap%5BuserName%5D=用户名&headMap%5Bsex%5D=性别&headMap%5Bbirthday%5D=生日
    @PostMapping("/exportByEntity")
    public void exportExcelByEntity(@RequestBody DynamicExcelParam dynamicExcelParam, HttpServletRequest request, HttpServletResponse response) throws Exception {

        dynamicExcelService.exportExcelByEntity(dynamicExcelParam,request,response);
//        return BaseResult.success("导出成功");
    }

    /**
     * 通过实体字段导入
     * @param entityName
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/importByEntity")
    public BaseResult importByEntity(String entityName, MultipartFile file) throws Exception {

        dynamicExcelService.importExcelByEntity(entityName,file.getInputStream());
        return BaseResult.success("导入成功");
    }

}
